import collections


class Solution(object):
    def minTime(self, n, edges, hasApple):
        p = [0] * n
        d = collections.defaultdict(set)
        for u, v in edges:
            d[u].add(v)
            d[v].add(u)
        p[0] = 1

        def dfs(u):
            ans = 0
            for v in d[u]:
                if not p[v]:
                    p[v] = 1
                    ans += dfs(v)
            if ans or hasApple[u]:
                return ans + 2
            else:
                return 0

        ans = dfs(0)
        if ans:
            return ans - 2
        else:
            return ans
